<template>
  <div class="profile-container">
    <a-card class="profile-card">
      <!-- 修改头像区域结构 -->
      <div class="avatar-section">
        <PictureUploader
          v-if="isEditing"
          biz="user_avatar"
          :value="userInfo.avatar"
          @change="(url) => (userInfo.avatar = url)"
          class="clickable-avatar"
        />
        <a-avatar v-else :size="100" :image-url="userInfo.avatar" />
      </div>

      <!-- 基本信息展示 -->
      <div v-if="!isEditing" class="info-section">
        <h2>{{ userInfo.username }}</h2>
        <p class="bio">{{ userInfo.bio || "暂无简介" }}</p>
        <div class="action-buttons">
          <a-button type="primary" @click="enterEditMode">编辑资料</a-button>
          <a-button @click="showChangePassword = true">修改密码</a-button>
        </div>
      </div>

      <!-- 编辑资料表单 -->
      <a-form
        v-else
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        layout="vertical"
        class="edit-form"
      >
        <a-form-item field="username" label="用户名">
          <a-input v-model="editForm.username" />
        </a-form-item>

        <a-form-item field="bio" label="个人简介">
          <a-textarea
            v-model="editForm.bio"
            :rows="3"
            placeholder="请输入个人简介"
          />
        </a-form-item>

        <div class="form-actions">
          <a-button @click="cancelEdit">取消</a-button>
          <a-button type="primary" @click="submitEdit">保存</a-button>
        </div>
      </a-form>
    </a-card>

    <!-- 新增我的应用模块 -->
    <a-card class="my-app-section" title="我的应用" style="margin-top: 24px">
      <a-table :data="appList">
        <template #columns>
          <a-table-column
            title="应用名称"
            data-index="appName"
          ></a-table-column>
          <a-table-column
            title="应用描述"
            data-index="appDesc"
          ></a-table-column>
          <a-table-column title="审核状态" data-index="reviewStatus">
            <template #cell="{ record }">
              <span v-if="record.reviewStatus === 0">待审核</span>
              <span v-else-if="record.reviewStatus === 1">通过</span>
              <span v-else-if="record.reviewStatus === 2">拒绝</span>
            </template>
          </a-table-column>
          <a-table-column title="操作">
            <template #cell="{ record }">
              <a-button type="text" @click="handleEditApp(record.id)"
                >编辑
              </a-button>
              <a-button
                type="text"
                status="danger"
                @click="handleDeleteApp(record)"
                >删除
              </a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 修改密码对话框 -->
    <a-modal
      v-model:visible="showChangePassword"
      title="修改密码"
      @ok="submitPasswordChange"
      @cancel="showChangePassword = false"
    >
      <a-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        layout="vertical"
      >
        <a-form-item field="oldPassword" label="旧密码">
          <a-input-password v-model="passwordForm.oldPassword" />
        </a-form-item>

        <a-form-item field="newPassword" label="新密码">
          <a-input-password v-model="passwordForm.newPassword" />
        </a-form-item>

        <a-form-item field="confirmPassword" label="确认密码">
          <a-input-password v-model="passwordForm.confirmPassword" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { Message } from "@arco-design/web-vue";
import { useLoginUserStore } from "@/store/userStore";
import PictureUploader from "@/components/PictureUploader.vue";
import axios from "axios";
import { updateAppUsingPost, deleteAppUsingPost } from "@/api/appController";

const loginUserStore = useLoginUserStore();
// 用户信息
const userInfo = reactive({
  username: loginUserStore.loginUser.userName,
  bio: loginUserStore.loginUser.userProfile,
  avatar: loginUserStore.loginUser.userAvatar,
});

// 编辑状态
const isEditing = ref(false);
const editForm = reactive({});
const editFormRef = ref(null);

// 密码修改相关
const showChangePassword = ref(false);
const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});
const passwordFormRef = ref(null);

// 新增应用相关状态
const appList = ref([]);
const currentApp = reactive({
  id: "",
  appName: "",
  appDesc: "",
  reviewStatus: "",
});
const editAppVisible = ref(false);

// 表单验证规则
const editRules = {
  username: [
    { required: true, message: "请输入用户名" },
    { minLength: 2, message: "用户名至少3个字符" },
  ],
};

const passwordRules = {
  oldPassword: [{ required: true, message: "请输入旧密码" }],
  newPassword: [
    { required: true, message: "请输入新密码" },
    { minLength: 6, message: "密码至少6位" },
  ],
  confirmPassword: [
    { required: true, message: "请确认密码" },
    {
      validator: (value, cb) => {
        if (value !== passwordForm.newPassword) {
          cb("两次输入密码不一致");
        } else {
          cb();
        }
      },
    },
  ],
};

// 进入编辑模式
const enterEditMode = () => {
  Object.assign(editForm, userInfo);
  isEditing.value = true;
};

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false;
};

// 提交编辑
const submitEdit = async () => {
  //控制台输出携带的数据
  console.log(editForm.username);
  try {
    // 发送退出请求
    const response = await axios.post(
      "http://localhost:8101/api/user/update",
      {
        id: loginUserStore.loginUser.id,
        userName: editForm.username,
        userProfile: editForm.bio,
        userAvatar: userInfo.avatar,
      },
      {
        headers: {
          Authorization: `Bearer ${localStorage.getItem("token")}`,
          type: "json",
          "Content-Type": "application/json",
        },
      }
    );
    if (response.data.code === 0) {
      // 更新store数据
      loginUserStore.$patch((state) => {
        state.loginUser = {
          ...state.loginUser,
          userName: editForm.username,
          userProfile: editForm.bio,
          userAvatar: editForm.avatar,
        };
      });

      // 同步本地用户信息
      Object.assign(userInfo, editForm);
      isEditing.value = false;
      Message.success("资料更新成功");

      // 移除强制刷新
      // window.location.reload();
    } else {
      Message.error("更新失败：" + response.data.message);
    }
  } catch (error) {
    console.log("表单验证失败");
  }
};

// 新增方法
const loadApps = async () => {
  try {
    const response = await axios.get(
      "http://localhost:8101/api/app/my/list/page/vo",
      {
        headers: {
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      }
    );
    console.log(response.data.data);
    appList.value = response.data.data;
  } catch (error) {
    Message.error("获取应用列表失败");
  }
};

const handleEditApp = (id) => {
  //跳转到http://localhost:8080/app/detail/{id}，当前页面跳转
  if (id) {
    window.location.replace(`http://localhost:8080/app/detail/${id}`);
  }
};

const handleDeleteApp = async (app) => {
  try {
    await deleteAppUsingPost({ id: app.id });
    Message.success("删除成功");
    await loadApps();
  } catch (error) {
    Message.error("删除失败");
  }
};

const submitAppEdit = async () => {
  try {
    await updateAppUsingPost(currentApp);
    Message.success("更新成功");
    editAppVisible.value = false;
    loadApps();
  } catch (error) {
    Message.error("更新失败");
  }
};

// 提交密码修改
const submitPasswordChange = async () => {
  try {
    // 发送退出请求
    const response = await axios.post(
      "http://localhost:8101/api/user/updatePassword",
      {
        oldPassword: passwordForm.oldPassword,
        newPassword: passwordForm.newPassword,
        checkNewPassword: passwordForm.confirmPassword,
      },
      {
        headers: {
          Authorization: `Bearer ${localStorage.getItem("token")}`,
          type: "json",
          "Content-Type": "application/json",
        },
      }
    );
    if (response.data.code === 0) {
      showChangePassword.value = false;
      Message.success("密码更新成功");
    } else {
      Message.error("更新失败：" + response.data.message);
    }
  } catch (error) {
    console.log("表单验证失败");
  }
};

// 初始化加载应用列表
onMounted(() => {
  loadApps();
});
</script>

<style scoped>
.profile-container {
  display: flex;
  flex-direction: column; /* 修改为垂直布局 */
  align-items: center; /* 保持居中 */
  padding: 40px 20px;
  background-color: var(--color-fill-2);
}

.profile-card {
  width: 100%;
  max-width: 600px;
  border-radius: 8px;
  margin-bottom: 24px; /* 添加底部间距 */
}

.avatar-section {
  text-align: center;
  margin-bottom: 24px;
}

/* 调整上传区域样式确保点击有效性 */
.avatar-upload-wrapper {
  display: inline-block; /* 改为行内块级元素保持头像居中 */
  position: relative;
}

/* 添加覆盖层提升点击感知 */
.avatar-upload-wrapper::after {
  content: "点击更换";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
  border-radius: 50%;
}

.avatar-upload-wrapper:hover::after {
  opacity: 1;
}

/* 确保上传组件充满头像容器 */
.clickable-avatar {
  cursor: pointer;
  border-radius: 50%;
  overflow: hidden;
  position: relative;
  width: 100px;
  height: 100px;
}

/* 添加hover提示效果 */
.clickable-avatar:hover .arco-upload-list-picture-mask {
  opacity: 1;
}

.arco-upload-list-picture-mask {
  background: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.info-section {
  text-align: center;
}

.bio {
  color: var(--color-text-2);
  margin: 16px 0;
  line-height: 1.6;
}

.action-buttons {
  margin-top: 24px;
  display: flex;
  gap: 12px;
  justify-content: center;
}

.edit-form {
  margin-top: 24px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

/* 新增应用表格样式 */
.my-app-section {
  width: 100%;
  max-width: 600px; /* 保持与资料卡片同宽 */
  margin-top: 24px;
}

.my-app-section :deep(.arco-table-tr) {
  line-height: 1.6;
}

.my-app-section :deep(.arco-table-th) {
  background-color: var(--color-fill-2);
}

/* 新增表单样式 */
.new-app-section {
  margin-top: 24px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 16px;
}
</style>
